package download

import (
	"sort"
	"sync"
)

type status struct {
	devId string
	speed int
}
type statusList []status

func (p statusList) Len() int {
	return len(p)
}

func (p statusList) Less(i, j int) bool {
	return p[i].speed > p[j].speed
}

func (p statusList) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

type statusSet struct {
	list statusList
	sync.RWMutex
	finalCount int
}

func (s *statusSet) Set(dev string, speedBytePs int) {
	s.Lock()
	defer s.Unlock()
	var found = false
	for i, v := range s.list {
		if v.devId == dev {
			found = true
			s.list[i].speed = speedBytePs
			break
		}
	}
	if !found {
		s.list = append(s.list, status{
			devId: dev,
			speed: speedBytePs,
		})
	}
}
func (s *statusSet) GetCount() int {
	s.RLock()
	defer s.RUnlock()
	return len(s.list)
}
func (s *statusSet) ShouldContinue(devid string) bool {
	if s.GetOrder(devid) < s.finalCount {
		return true
	}
	return false
}
func (s *statusSet) GetOrder(devid string) int {
	s.Lock()
	defer s.Unlock()
	sort.Sort(s.list)

	for i, item := range s.list {
		if item.devId == devid {
			return i
		}
	}
	return len(s.list)
}
